package com.lagou.utils;

import java.sql.*;

/**
 * @Author wsl
 * @Date 2021/8/18 20:48
 * @Project_Name mysql
 *
 * JDBC工具类
 */
public class JDBCUtils {

    //1.将连接信息定义为 字符串常量
    public static final String DRIVERNAME = "com.mysql.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/db4?useUnicode=true&characterEncoding=UTF-8";
    public static final String USER = "root";
    public static final String PASSWORD = "123456";

    //2.静态代码块
    static {
        //1.注册驱动
        try {
            Class.forName(DRIVERNAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //3.获取连接的 静态方法
    public static Connection getConnection(){
        //2.获取连接对象 并返回
        try {
            Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
            return  connection;
        } catch (SQLException e) {
            e.printStackTrace();
            return  null;
        }
    }

    //4.关闭资源的方法
    public static void close(Connection con, Statement statement){
           if (null != con && null != statement){
               try {
                   statement.close();
                   con.close();
               } catch (SQLException e) {
                   e.printStackTrace();
               }
           }
    }

    //5.查询方法关闭
    public static void close(Connection con, Statement statement, ResultSet resultSet){
        if (null != con && null != statement && null != resultSet){
            try {
                resultSet.close();
                statement.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
